const express = require(`express`)
const router = express.Router()
const mongoose = require('mongoose');
const trans  = require('./myglobal').trans;
const Teacher = mongoose.model('Teacher');
// Teacher.find({number:'10347'}).exec((err,doc)=>{
//     var j=2;
// });
router.get('/teacher',async (req,res,next)=>{
    //
    try{
       
        var teachers = Teacher.find(JSON.parse(req.query.query));
        console.log("sessionID "+req.sessionID);
        if( trans[req.sessionID])
        teachers.session( trans[req.sessionID])
       if(req.query.populate)
       {
            req.query.populate.forEach(p=>{
            teachers.populate(JSON.parse(p))
        })
    }
        if(req.query.skip)
        teachers.skip(JSON.parse(req.query.skip))
       if(req.query.limit)
        teachers.skip(JSON.parse(req.query.limit))
        if(req.query.sort)
        teachers.sort(JSON.parse(req.query.sort));
        var result = await teachers.exec();
        res.jsonp(result);
    }catch(e){
        res.status(500).send(e);
    }
    //
});
router.delete('/teacher',async (req,res,next)=>{
    try{
    var removeQuery =  Teacher.deleteMany(req.body.query);
    if( trans[req.sessionID])
    removeQuery.session( trans[req.sessionID])
    var result = await removeQuery.exec();
    res.jsonp(result);
    }catch(e){
        res.status(500).send(e);
    }
})
router.post('/teacher',async (req,res,next)=>{
    try{
        var results = null;
        if( trans[req.sessionID])
         results = await Teacher.create(req.body, { session:  trans[req.sessionID] });
        else
        results = await Teacher.create(req.body);
         res.jsonp(results);
    }catch(e){
        res.status(500).send(e);
    }
})
router.put('/teacher',async (req,res,next)=>{
    try{
    var updateQuery =  Teacher.updateMany(req.body.query,req.body.update);
    if( trans[req.sessionID])
    updateQuery.session( trans[req.sessionID])
    var result =  await updateQuery.exec();
    res.jsonp(result);
    }catch(e){
        res.status(500).send(e);
    }
})
module.exports = router